package cn.gailvlun.gll.presentation.hotel.drawer

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.os.IBinder
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.gailvlun.gll.R
import cn.gailvlun.gll.bean.PlaceHolder
import cn.gailvlun.gll.chatkit.PlayerService
import cn.gailvlun.gll.databinding.FragmentHotelShareAudioBinding
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.ListRes
import cn.gailvlun.gll.net.NewQueryParam
import cn.gailvlun.gll.net.hotel.InsomniaHotel
import cn.gailvlun.gll.net.hotel.InsomniaType
import cn.gailvlun.gll.presentation.base.App
import cn.gailvlun.gll.presentation.base.BaseFragment
import cn.gailvlun.gll.presentation.hotel.widget.DividerDecoration
import cn.gailvlun.gll.util.*
import cn.gailvlun.gll.widget.PlayButton
import cn.gailvlun.gll.widget.PlayState
import com.github.markzhai.recyclerview.BaseViewAdapter
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener


class HotelShareAudioFragment : BaseFragment(), OnRefreshListener, OnLoadmoreListener {
    private lateinit var mBinding: FragmentHotelShareAudioBinding

    private lateinit var mAdapter: HotelAudioShareAdapter
    private lateinit var mLayoutManager: LinearLayoutManager

    private val newQueryParam = NewQueryParam()

    private var mBinder: PlayerService.PlayerBinder? = null
    private val mServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            mBinder = service as PlayerService.PlayerBinder
        }

        override fun onServiceDisconnected(name: ComponentName) {
            mBinder = null
        }
    }

    override fun initComponent(inflater: LayoutInflater, container: ViewGroup?): View {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_hotel_share_audio, container, false)

        mAdapter = HotelAudioShareAdapter(mContext)
        mAdapter.setPresenter(Presenter())
        mBinding.recyclerView.adapter = mAdapter

        mLayoutManager = LinearLayoutManager(mContext)
        mBinding.recyclerView.layoutManager = mLayoutManager
        mBinding.recyclerView.addItemDecoration(DividerDecoration(mContext,R.color.transparent))

        mBinding.srl.setOnRefreshListener(this)

        val intent = Intent(mContext, PlayerService::class.java)
        mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)

        return mBinding.root
    }

    override fun createHandler() {

    }

    override fun loadData(savedInstanceState: Bundle?) {
        mBinding.srl.autoRefresh()
    }

    override fun onRefresh(refreshlayout: RefreshLayout?) {
        HttpMethods.getHotelService()
                .getMineInsomniaList(InsomniaType.V, null, null, null, null, null)
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<ListRes<InsomniaHotel>>() {
                    override fun onSuccess(response: ListRes<InsomniaHotel>?) {
                        loadRecyclerView(response?.results, true, response?.isNext)
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<InsomniaHotel>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)
                    }

                    override fun onFinish() {
                        super.onFinish()
                        mBinding.srl.finishRefresh()
                    }
                })
    }

    override fun onLoadmore(refreshlayout: RefreshLayout?) {
        newQueryParam.lastId = mAdapter.getLastId()
        newQueryParam.direction = NewQueryParam.next
        HttpMethods.getHotelService()
                .getMineInsomniaList(InsomniaType.V, null, null, newQueryParam.lastId,
                        newQueryParam.direction, null)
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<ListRes<InsomniaHotel>>() {
                    override fun onSuccess(response: ListRes<InsomniaHotel>?) {
                        loadRecyclerView(response?.results, false, response?.isNext)
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<InsomniaHotel>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)
                    }

                    override fun onFinish() {
                        super.onFinish()
                        mBinding.srl.finishLoadmore()
                    }
                })
    }

    fun loadRecyclerView(list: List<InsomniaHotel>?, isRefresh: Boolean, isMore: Boolean?) {
        if (isRefresh) {
            mAdapter.clear()
            if (IsEmpty.list(list)) {
                
            } else {
                mAdapter.addAll(list)
            }
        } else {
            mAdapter.addAll(list)
        }

        mBinding.srl.isEnableLoadmore = isMore!!
    }

    override fun isLazyLoad() = true

    inner class Presenter : BaseViewAdapter.Presenter {
        fun onDelete(item: InsomniaHotel) {
            val pd = DialogUtil.showIndeterminate(mContext)
            HttpMethods.getHotelService()
                    .deleteInsomnia(item.id)
                    .compose(RxUtil.applyScheduler())
                    .compose(bindToLifecycle())
                    .subscribe(object : HttpSubscriber<PlaceHolder>() {
                        override fun onSuccess(response: PlaceHolder?) {
                            ToastUtil.showShort(getString(R.string.hotel_drawer_audio_deletion))
                            mAdapter.deleteItem(item)
                        }

                        override fun onFailure(errMsg: String?, response: PlaceHolder?, code: Int) {
                            DialogUtil.showError(mContext, errMsg)
                        }

                        override fun onFinish() {
                            super.onFinish()
                            pd.dismiss()
                        }
                    })
        }

        fun onPlayChanged(pb: PlayButton, playState: PlayState, item: InsomniaHotel) {
            when (playState) {
                PlayState.READY_TO_PLAY -> {
                    

                    mBinder?.stopAudio()
                }
                PlayState.PLAYING -> {
                    

                    mBinder?.playAudio(item.audio)
                    mBinder?.setOnCompletionListener {
                        pb.stop()
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        mBinder?.stopAudio()
        mContext.unbindService(mServiceConnection)
        super.onDestroy()
    }

    object Util {
        @JvmStatic
        fun getUnderText(item: InsomniaHotel): String {
            return "${DateUtil.format(DateUtil.NO_SECOND_PATTERN, item.created)} ${getLongFromMill(item.audio_length)}"
        }

        @JvmStatic
        private fun getLongFromMill(mill: Int?): String {

            val res = App.getInstance().resources
            return if (mill != null) {
                StringUtil.format(res.getString(R.string.hotel_drawer_time_format), mill.div(60), mill % 60)
            } else {
                res.getString(R.string.hotel_time_format_default)
            }
        }
    }

}